<template>
  <lay-container fluid="true" style="padding: 10px">
    <lay-row space="10">
      <lay-col md="6" v-show="btnIcon">
        <lay-card>
          <lay-input
            placeholder="请输入角色名称"
            size="xs"
            :allow-clear="true"
            v-model="searchMsg"
            @blur="GetRoleInfosList"
            @clear="GetRoleInfosList"
          ></lay-input>
          <lay-row space="10" class="header_left">
            <lay-col md="12">
              <div
                v-for="(item, index) in roleList"
                :key="index"
                @click="bgcIndex = index"
              >
                <lay-tooltip :is-dark="false">
                  <template #content>
                    <lay-button
                      border="green"
                      size="sm"
                      v-if="httpUrls.includes('/Setting/AddorUpdateRoleInfo')"
                      @click="editBumen(item)"
                      >编辑
                    </lay-button>
                    <lay-button
                      border="red"
                      size="sm"
                      v-if="httpUrls.includes('/Setting/DeleteRoleInfo')"
                      @click="dleBumen(item)"
                      >删除
                    </lay-button>
                  </template>
                  <lay-tag class="mtop" :color="index === bgcIndex ? '#165DFF' : ''">
                    {{ item.roleName }}
                  </lay-tag>
                </lay-tooltip>
              </div>
            </lay-col>
            <lay-col md="6" mdOffset="6">
              <lay-button
                size="sm"
                type="primary"
                @click="addRole"
                v-if="httpUrls.includes('/Setting/AddorUpdateRoleInfo')"
                >添加角色</lay-button
              >
            </lay-col>
          </lay-row>
        </lay-card>
      </lay-col>
      <lay-col :md="btnIcon ? 18 : 24">
        <lay-card>
          <div>
            <span @click="btnIcon = !btnIcon">
              <i class="layui-icon layui-icon-shrink-right" v-if="btnIcon"></i>
              <i class="layui-icon layui-icon-spread-left" v-else></i>
            </span>
            <h1 v-if="roleList.length">角色名称：{{ roleList[bgcIndex].roleName }}</h1>
            <lay-row space="10" class="header_right">
              <lay-col md="12">
                <div
                  v-for="(item, index) in tabList"
                  :key="index"
                  class="tab_imte"
                  @click="itemBgc = index"
                  :class="[index === itemBgc ? 'tab_border' : '']"
                >
                  {{ item.name }}
                </div>
              </lay-col>
              <lay-col md="4" mdOffset="8">
                <lay-button
                  size="sm"
                  type="primary"
                  @click="editRoleTable"
                  v-if="httpUrls.includes('/Setting/GetAccessPages')"
                  >编辑</lay-button
                >
                <lay-button
                  size="sm"
                  type="primary"
                  @click="addUser"
                  v-if="httpUrls.includes('/Setting/RoleAssignment')"
                  >人员管理</lay-button
                >
              </lay-col>
            </lay-row>
          </div>
          <myTable
            v-if="roleList.length"
            :dataSource="getMenuTablist(myTableList)"
          ></myTable>
        </lay-card>
      </lay-col>
    </lay-row>

    <lay-layer
      type="drawer"
      v-model="visible"
      title="人员管理"
      area="50%"
      :btn="addUSerBtn"
      class="user_box"
    >
      <lay-row space="10">
        <lay-card>
          <lay-col md="24" class="left_input" mdOffset="1">
            <div>
              <div v-for="(item, index) in userList" :key="index" class="checkout_item">
                <lay-checkbox
                  name="like"
                  skin="primary"
                  v-model="item.checked"
                  :value="item.userid"
                  :label="item.username"
                ></lay-checkbox>
              </div>
            </div>
          </lay-col>
        </lay-card>
      </lay-row>

      <!-- <div class="layer-footer">
        <lay-button
          type="primary"
          @click="visible = false"
        >确定</lay-button>
        <lay-button @click="visible = false">取消</lay-button>
      </div> -->
    </lay-layer>

    <lay-layer
      type="drawer"
      v-model="editVisible"
      title="编辑权限"
      area="800px"
      :btn="editBtn"
    >
      <editRoles
        v-if="editVisible"
        :dataSource="[...editRolesTable]"
        @claears="claears"
      />
    </lay-layer>

    <lay-layer
      :title="titles"
      v-model="addVisible"
      :btn="btn"
      area="300px"
      :offset="['200px', '200px']"
    >
      <div class="add_role">
        <lay-input placeholder="请输入角色" v-model="roleName"></lay-input>
      </div>
    </lay-layer>

    <lay-layer
      title="提示"
      v-model="delVisible"
      :btn="delBumrnAlter"
      area="300px"
      :offset="['200px', '200px']"
    >
      <div class="add_del">确定删除该角色？</div>
    </lay-layer>
  </lay-container>
</template>

<script lang="ts">
import { reactive, ref, toRefs, onMounted } from "vue";
import myTable from "./component/table.vue";
import editRoles from "./component/editRole.vue";
import {
  GetRoleInfos,
  AddorUpdateRoleInfo,
  DeleteRoleInfo,
  GetAccessPages,
  GetUsers,
  RoleAssignment,
} from "../../../api/module/user";
import { number } from "@intlify/core-base";
export default {
  components: {
    myTable,
    editRoles,
  },
  setup() {
    const checkbox = ref(true);

    const columns = [
      {
        title: "菜单",
        customSlot: "menu",
      },
      {
        title: "模块",
        customSlot: "model",
      },
      {
        title: "功能",
        customSlot: "gongn",
      },
      {
        title: "操作",
        customSlot: "look",
      },
      {
        title: "人员",
        customSlot: "user",
      },
    ];

    let dataSource: any = [];

    onMounted(() => {
      // httpUrl
      if (data.httpUrls.includes("/Setting/GetRoleInfos")) {
        GetRoleInfosList();
      }

      if (data.httpUrls.includes("/Setting/GetAccessPages")) {
        getTablist();
      }
    });

    const getTablist = async () => {
      const res: any = await GetAccessPages({
        pageIndex: 1,
        pagePerCount: 100,
        condition: "",
      });
      if (res.code === 200) {
        if (res.data.datas.length) {
          let list: any = res.data.datas.reverse();
          data.myTableList = getMecusTabl(list);
        }
      }
    };

    const getMecusTabl = (list: any) => {
      let arrMenus: any = [];
      let url1: any = [
        "/Checkmsg/CheckPointUpload",
        "/Checkmsg/ObjectStatusCountSta",
        "/Checkmsg/GetUnclaims",
        "/Checkmsg/DelUnclaims",
        "/Checkmsg/DoClaim",
        "/Checkmsg/GetSubmitting",
        "/Checkmsg/DoCheckPending",
        "/Checkmsg/GetCheckPending",
        "/Checkmsg/DoExamine",
        "/Checkmsg/GetExamine",
        "/Checkmsg/DoSignissue",
        "/Checkmsg/GetSignissue",
        "/Checkmsg/DoFile",
        "/Checkmsg/GetFiledlist",
        "/Setting/GetTestItemInfo",
        "/Setting/GetDeviceInfos",
        "/Setting/GetUserNameList",
        "/Checkmsg/TestItemModify",
        "/Setting/GetUsers",
        "/Checkmsg/SubmittingBack",
        "/Checkmsg/CheckPendingBack",
        "/Checkmsg/ExamineBack",
        "/Checkmsg/SignissueBack",
      ];

      let url2: any = [
        // "/Checkmsg/ObjectStatusCountSta",
        // "/Checkmsg/GetUnclaims",
        // "/Checkmsg/GetSubmitting",
        // "/Checkmsg/GetCheckPending",
        // "/Checkmsg/GetExamine",
        // "/Checkmsg/GetSignissue",
        // "/Checkmsg/GetFiledlist",
        "/Checkmsg/GetPersonSta",
        "/Checkmsg/GetPersonStaReport",
        "/Setting/GetTestItemInfo",
        "/Checkmsg/DetectionObjectSearch",
      ];

      let url3: any = [
        "/Checkmsg/GetPersonSta",
        "/Checkmsg/GetProjectSta",
        "/Checkmsg/GetProjectStaReport",
      ];

      let url4: any = [
        "/Setting/GetUsers",
        "/Setting/InsertorUpdateUser",
        "/Setting/DeleteUser",
        "/Setting/GetDepartmentInfo",
        "/Setting/AddorUpdateDepartmentInfo",
        "/Setting/DelDepartmentInfo",
      ];

      let url5: any = [
        "/Setting/GetRoleInfos",
        "/Setting/AddorUpdateRoleInfo",
        "/Setting/DeleteRoleInfo",
        "/Checkmsg/SystemChange",
        "/Setting/GetAccessPages",
        "/Setting/RoleAssignment",
        "/Setting/GetUserNameList",
      ];

      let url6: any = [
        "/Setting/DevicelistUpload",
        "/Setting/GetDeviceInfos",
        "/Setting/InsertorUpdateDevice",
        "/Setting/DeleteDevice",
      ];

      let url7: any = [
        "/Setting/RoleAssignment",
        "/Checkmsg/DetectionObjectSearch",
        "/Checkmsg/GetCheckProcess",
        "/Setting/GetTestItemInfo",
        "/Checkmsg/DetectionObjectSearchOutput"

      ];

      let url8: any = [
        "/Setting/GetTestItemInfo",
        "/Setting/AddorUpdateTestItemInfo",
        // "/Setting/DelTestItemInfo",
      ];

      let btnList1: any = [];
      let btnList2: any = [];
      let btnList3: any = [];
      let btnList4: any = [];
      let btnList5: any = [];
      let btnList6: any = [];
      let btnList7: any = [];
      let btnList8: any = [];
      let model1: any = {};
      let model2: any = {};
      let model3: any = {};
      let model7: any = {};

      let model4: any = {};
      let model5: any = {};
      let model6: any = {};
      let model8: any = {};
      list.forEach((item: any) => {
        if (
          url4.includes(item.url) ||
          url5.includes(item.url) ||
          url6.includes(item.url) ||
          url8.includes(item.url) ||
          item.url == "/system/cssx" ||
          item.url == "/system/user" ||
          item.url == "/system/role" ||
          item.url == "/system/equipment" ||
          item.url == "/system"
        ) {
          if (url4.includes(item.url)) {
            btnList4.push(item);
          }

          if (item.url == "/system/user") {
            item.btnList = [];
            item.btnList = btnList4;

            model4 = {
              ...item,
            };
          }

          if (url5.includes(item.url)) {
            btnList5.push(item);
          }

          if (item.url == "/system/role") {
            item.btnList = [];
            item.btnList = btnList5;
            model5 = {
              ...item,
            };
          }

          if (url6.includes(item.url)) {
            btnList6.push(item);
          }

          if (url8.includes(item.url)) {
            btnList8.push(item);
          }

          if (item.url == "/system/equipment") {
            item.btnList = [];
            item.btnList = btnList6;
            model6 = {
              ...item,
            };
          }

          if (item.url == "/system/cssx") {
            item.btnList = [];
            item.btnList = btnList8;
            model8 = {
              ...item,
            };
          }

          if (item.url == "/system") {
            item.model = [];
            item.model.push(model4);
            item.model.push(model5);
            item.model.push(model6);
            item.model.push(model8);
            arrMenus.push(item);
            console.log("arrMenus", arrMenus);
          }
        }

        if (
          url1.includes(item.url) ||
          url2.includes(item.url) ||
          url3.includes(item.url) ||
          url7.includes(item.url) ||
          item.url == "/workspace/zhcx" ||
          item.url == "/workspace/workbench" ||
          item.url == "/workspace/console" ||
          item.url == "/workspace/analysis" ||
          item.url == "/workspace"
        ) {
          if (url1.includes(item.url)) {
            btnList1.push(item);
          }

          if (item.url == "/workspace/workbench") {
            item.btnList = [];
            item.btnList = btnList1;

            model1 = {
              ...item,
            };
          }

          if (url2.includes(item.url)) {
            btnList2.push(item);
          }

          if (item.url == "/workspace/console") {
            item.btnList = [];
            item.btnList = btnList2;
            model2 = {
              ...item,
            };
          }

          if (url3.includes(item.url)) {
            btnList3.push(item);
          }

          if (url7.includes(item.url)) {
            btnList7.push(item);
          }

          if (item.url == "/workspace/analysis") {
            item.btnList = [];
            item.btnList = btnList3;
            model3 = {
              ...item,
            };
          }

          if (item.url == "/workspace/zhcx") {
            item.btnList = [];
            item.btnList = btnList7;
            model7 = {
              ...item,
            };
          }

          if (item.url == "/workspace") {
            item.model = [];
            item.model.push(model1);
            item.model.push(model2);
            item.model.push(model3);
            item.model.push(model7);
            arrMenus.push(item);
          }
        }
      });
      console.log("arrMenus-**", arrMenus);

      return arrMenus.reverse();
    };

    const GetRoleInfosList = async () => {
      const res: any = await GetRoleInfos({
        pageIndex: 1,
        pagePerCount: 100,
        condition: data.searchMsg,
      });
      if (res.code === 200) {
        data.roleList = res.data.datas;
      }
    };

    const getMenuTablist = (list: any) => {
      let tabList: any = [];
      tabList.push(data.roleList[data.bgcIndex]);
      console.log("tabList", tabList);

      return tabList;
    };
    let httpUrl: any = [];
    httpUrl = sessionStorage.getItem("httpUrl");
    httpUrl = JSON.parse(httpUrl);
    const data = reactive({
      httpUrls: httpUrl,
      value: "" as any,
      userList: [] as any,
      stat: "",
      typeBm: "",
      titles: "",
      roleName: "",
      searchMsg: "",
      roleId: 0,
      bgcIndex: 0,
      itemBgc: 0,
      userVisible: false,
      delVisible: false,
      addVisible: false,
      visible: false,
      checked: false,
      editVisible: false,
      btnIcon: true,
      editRolesTable: [] as any,
      menuListTable: [] as any,
      pageIds: [] as any,
      apiIds: [] as any,
      roleList: [] as any,
      myTableList: [] as any,
      tabList: [
        {
          name: "建委系统权限",
        },
        {
          name: "交委系统权限",
        },
      ],
    });

    const addRole = () => {
      data.roleId = 0;
      data.roleName = "";
      data.typeBm = "add";
      data.titles = "添加角色";
      data.addVisible = true;
    };

    const rowClick = (data: any) => {
      console.log(JSON.stringify(data));
    };

    const rowDoubleClick = (data: any) => {
      console.log(JSON.stringify(data));
    };

    const btn = [
      {
        text: "确认",
        callback: async () => {
          console.log("AddorUpdateRoleInfo");

          const res: any = await AddorUpdateRoleInfo({
            roleName: data.roleName,
            roleId: data.roleId ? data.roleId : 0,
          });
          if (res.code === 200) {
            data.addVisible = false;
            GetRoleInfosList();
          }
        },
      },
      {
        text: "取消",
        callback: () => {
          // alert("取消事件");
          data.addVisible = false;
        },
      },
    ];

    const editBumen = (item: any) => {
      data.typeBm = "edit";
      data.titles = "编辑角色";
      data.roleName = item.roleName;
      data.roleId = item.roleId;
      data.addVisible = true;
    };

    const dleBumen = (item: any) => {
      data.delVisible = true;
      data.roleId = item.roleId;
    };

    const delBumrnAlter = [
      {
        text: "确认",
        callback: async () => {
          const res: any = await DeleteRoleInfo({
            roleId: data.roleId,
          });
          if (res.code === 200) {
            data.roleId = 0;
            data.delVisible = false;
            GetRoleInfosList();
          }
        },
      },
      {
        text: "取消",
        callback: () => {
          data.delVisible = false;
        },
      },
    ];

    const delUserAlter = [
      {
        text: "确认",
        callback: async () => {
          // const res: any = await DeleteUser({
          //   userid: data.roleId,
          // });
          // if (res.code === 200) {
          //   data.roleId = 0;
          //   data.userVisible = false;
          //   // getUser();
          // }
        },
      },
      {
        text: "取消",
        callback: () => {
          data.userVisible = false;
        },
      },
    ];

    const addUser = () => {
      getSelect();
      
    };

    const getSelect = async () => {
      const res: any = await GetUsers({
        pageIndex: 1,
        pagePerCount: 500,
        condition: {
          roleId: data.roleId ? data.roleId : null,
        },
      });
      if (res.code == 200) {
    
        console.log("data.roleList[data.bgcIndex]-9999999999999999", data.roleList[data.bgcIndex].persons);
        let users: any = [];
        if (data.roleList[data.bgcIndex].persons) {
          users = data.roleList[data.bgcIndex].persons.split(",");
        }
        console.log('users', users);
        
        res.data.datas.map((item: any) => {
          item.checked = false;
          if (users.includes(item.username)) {
            item.checked = true;
          }
        });
        data.userList = res.data.datas;
        data.visible = true;
      }
    };

    const claears = () => {
      data.editVisible = false;
    };

    const editRoleTable = () => {
      console.log("data.bgcIndex", data.bgcIndex);
      console.log("data.apiIds", data.roleList[data.bgcIndex].apiIds);
      console.log("data.pageIds", data.roleList[data.bgcIndex].pageIds);
      data.editRolesTable = [];
      data.myTableList.map((item: any) => {
        item.model.map((items: any) => {
          items.selected = false;
          items.btnList.map((ites: any) => {
            ites.selected = false;
          });
        });
      });

      if (
        data.roleList[data.bgcIndex].pageIds.length ||
        data.roleList[data.bgcIndex].apiIds.length
      ) {
        let apiIds: any = [];
        apiIds = data.roleList[data.bgcIndex].apiIds.split(",");
        let arr: any = [];
        arr = data.roleList[data.bgcIndex].pageIds.split(",");
        console.log("arr", arr);

        let arrs = [...apiIds, ...arr];
        console.log("arrs", arrs);

        let list = arrs.map(Number);
        console.log("listlist", list);
        console.log("data.myTableList", data.myTableList);

        data.myTableList.map((item: any) => {
          item.model.map((items: any) => {
            if (list.includes(items.accessPageId)) {
              items.selected = true;
            }

            items.btnList.map((ites: any) => {
              if (list.includes(ites.accessPageId)) {
                ites.selected = true;
              }
            });
          });
        });
        data.editRolesTable = data.myTableList;
        console.log(" data.editRolesTable", data.editRolesTable);

        data.editVisible = true;
      } else {
        data.myTableList.map((item: any) => {
          item.model.map((items: any) => {
            items.selected = false;
            items.btnList.map((ites: any) => {
              ites.selected = false;
            });
          });
        });
        data.editRolesTable = data.myTableList;
        data.editVisible = true;
      }
    };

    const editBtn = [
      {
        text: "确认",
        callback: async () => {
          data.pageIds = [];
          data.apiIds = [];
          let arr: any = [...data.myTableList];
          arr.forEach((item: any) => {
            item.model.forEach((items: any) => {
              if (items.isPage && items.selected) {
                data.pageIds.push(items.accessPageId);

                if (items.url.substr(0, 10) === "/workspace") {
                  data.pageIds.push(item.accessPageId);
                }

                if (items.url.substr(0, 7) === "/system") {
                  data.pageIds.push(item.accessPageId);
                }
              }
              items.btnList.forEach((row: any) => {
                if (!row.pageIds && row.selected) {
                  data.apiIds.push(row.accessPageId);
                }
              });
            });
          });
          let apiIds: any = new Set(data.apiIds);
          apiIds = [...apiIds];

          let pageIds: any = new Set(data.pageIds);
          pageIds = [...pageIds];

          console.log("pageIds", pageIds);
          console.log("apiIds", apiIds);
          // return;
          const res: any = await AddorUpdateRoleInfo({
            roleName: data.roleList[data.bgcIndex].roleName
              ? data.roleList[data.bgcIndex].roleName
              : 0,
            roleId: data.roleList[data.bgcIndex].roleId
              ? data.roleList[data.bgcIndex].roleId
              : 0,
            pageIds: pageIds.join(","),
            apiIds: apiIds.join(","),
            dataAccess: "",
          });
          if (res.code === 200) {
            data.editVisible = false;
            GetRoleInfosList();
          }
        },
      },
      {
        text: "取消",
        callback: () => {
          data.editVisible = false;
        },
      },
    ];
    const roleIds: any = ref();
    const addUSerBtn = [
      {
        text: "确认",
        callback: async () => {
          let arr: any = [];
          if (data.userList.length) {
            data.userList.forEach((item: any) => {
              if (item.checked) {
                arr.push(item.userid);
              }
            });
          }
          console.log(' arr.length ? arr.join(",") : null',  arr.length ? arr.join(",") : null);
          
          // if (arr.length) {
            const res: any = await RoleAssignment({
              roleId: data.roleList[data.bgcIndex].roleId,
              userIds: arr.length ? arr.join(",") : null,
            });

            if (res.code == 200) {
              data.visible = false;
              GetRoleInfosList();
            }
          // }
        },
      },
      {
        text: "取消",
        callback: () => {
          data.visible = false;
        },
      },
    ];

    return {
      editBtn,
      checkbox,
      roleIds,
      editRoleTable,
      getSelect,
      dleBumen,
      editBumen,
      rowClick,
      rowDoubleClick,
      addUser,
      dataSource,
      columns,
      btn,
      delBumrnAlter,
      addRole,
      addUSerBtn,
      GetRoleInfosList,
      claears,
      getMenuTablist,
      ...toRefs(data),
    };
  },
};
</script>

<style>
.user_box .layui-card.is-hover-shadow:hover,
.layui-card.shadow {
  box-shadow: none;
}
</style>

<style lang="scss" scoped>
.header_left {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eeeeee;
  margin: 12px 0;
  padding-top: 8px;

  div {
    cursor: pointer;
  }

  .left_jurisdiction {
    width: 100%;
  }
}

.header_right {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // border-top: 1px solid #eeeeee;
  margin: 12px 0;
  padding-top: 8px;
}
.add_del {
  margin: 10px 20px;
}
.textColor {
  color: #0066ff;
}

.mtop {
  margin-bottom: 10px;
}

.tab_imte {
  height: 40px;
  line-height: 40px;
  display: inline-block;
  align-items: center;
  margin-right: 22px;
  border-bottom: 2px solid transparent;
  margin-bottom: 8px;
}

.tab_border {
  color: #0066ff;
  border-bottom: 2px solid #0066ff;
}

h1 {
  font-weight: 700;
}

.layer-footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 50px;
  line-height: 50px;
  border-top: 1px solid #eeeeee;
  margin-left: 18px;
}

.checkout_item {
  display: inline-block;
  margin: 10px 0;
  border: 1px solid #eeeeee !important;
  margin-right: 18px;
  padding: 0 4px;
}

.lay-table {
  margin-top: 18px;
}

.tables {
  margin: 18px;
}

.technology {
  margin-top: 12px;
}

.add_role {
  margin: 10px 20px;
}
</style>
